package com.bob.light

import android.content.Context
import com.bob.light.Tools.isMainProcess
import com.bob.light.config.AppConfig
import com.tuya.smart.android.common.utils.L
import com.tuya.smart.android.user.api.ILoginCallback
import com.tuya.smart.android.user.api.IRegisterCallback
import com.tuya.smart.android.user.bean.User
import com.tuya.smart.home.sdk.TuyaHomeSdk
import com.tuya.smart.home.sdk.api.ITuyaHomeChangeListener
import com.tuya.smart.home.sdk.bean.HomeBean
import com.tuya.smart.home.sdk.builder.ActivatorBuilder
import com.tuya.smart.home.sdk.callback.ITuyaGetHomeListCallback
import com.tuya.smart.home.sdk.callback.ITuyaHomeResultCallback
import com.tuya.smart.sdk.api.IResultCallback
import com.tuya.smart.sdk.api.ITuyaActivator
import com.tuya.smart.sdk.api.ITuyaActivatorGetToken
import com.tuya.smart.sdk.api.ITuyaSmartActivatorListener
import com.tuya.smart.sdk.bean.DeviceBean
import com.tuya.smart.sdk.enums.ActivatorModelEnum


object TuyaHomeSDKHelper {

    @JvmStatic
    fun init() {
        if (isMainProcess(AppConfig.application())) {
            hookLog("tuya sdk init success")
            TuyaHomeSdk.init(AppConfig.application())
            TuyaHomeSdk.setDebugMode(AppConfig.isDebug())
        }
    }

    @JvmStatic
    fun destroy() {
        if (isMainProcess(AppConfig.application())) {
            hookLog("tuya sdk destroy success")
            TuyaHomeSdk.onDestroy()
        }
    }

    @JvmStatic
    fun checkLogin(): Boolean {
        hookLog("tuya sdk check login state")
        return TuyaHomeSdk.getUserInstance().isLogin
    }

    /**
     * @author xhb
     * @version 1.0.0
     * @desc 用户管理 手机号+密码登陆操作
     */
    @JvmStatic
    fun loginWithPhonePasswordInChina(phone: String, pwd: String, successCallback: ((user: User?) -> Unit)? = null,
                         failCallback: (() -> Unit)? = null) {
        TuyaHomeSdk.getUserInstance().loginWithPhonePassword("86", phone, pwd,
            object : ILoginCallback {
                override fun onSuccess(user: User?) {
                    hookLog("tuya sdk login with phone pwd success")
                    hookLog("tuya sdk login user is -- > ${user?.toString()}")
                    AppConfig.uiHandler().post {
                        successCallback?.invoke(user)
                    }
                }

                override fun onError(code: String?, error: String?) {
                    hookLog("tuya sdk login with phone pwd error")
                    hookLog("tuya sdk login code = $code, error = $error")
                    AppConfig.uiHandler().post {
                        failCallback?.invoke()
                    }
                }
            })
    }

    @JvmStatic
    fun sendVerifyCodeWithPhoneInChina(phone: String, successCallback: (() -> Unit)? = null,
                                       failCallback: (() -> Unit)? = null) {
        //区域，默认填写：“” 即可
        val region = ""
        TuyaHomeSdk.getUserInstance().sendVerifyCodeWithUserName(phone, region, "86", 1,
                object : IResultCallback {
                    override fun onSuccess() {
                        hookLog("tuya sdk register send code success")
                        AppConfig.uiHandler().post {
                            successCallback?.invoke()
                        }
                    }

                    override fun onError(code: String?, error: String?) {
                        hookLog("tuya sdk register send code fail")
                        hookLog("tuya sdk register send code = $code, error = $error")
                        AppConfig.uiHandler().post {
                            failCallback?.invoke()
                        }
                    }
                })
    }

    @JvmStatic
    fun registerAccountWithPhoneInChina(phone: String, pwd: String, code: String,
                                        successCallback: (() -> Unit)? = null,
                                        failCallback: (() -> Unit)? = null) {
        TuyaHomeSdk.getUserInstance().registerAccountWithPhone("86", phone, pwd, code,
                object : IRegisterCallback {
                    override fun onSuccess(user: User?) {
                        hookLog("tuya sdk register with phone pwd success")
                        AppConfig.uiHandler().post {
                            successCallback?.invoke()
                        }
                    }

                    override fun onError(code: String?, error: String?) {
                        AppConfig.uiHandler().post {
                            hookLog("tuya sdk register with phone pwd error")
                            hookLog("tuya sdk register with phone pwd code = $code, error = $error")
                            failCallback?.invoke()
                        }
                    }
                })
    }

    /**
     * @author xhb
     * @version 1.0.0
     * @desc 家庭管理 查询家庭列表
     */
    @JvmStatic
    fun queryFamilyList(successCallback: ((homeBeans: MutableList<HomeBean>?) -> Unit)?) {
        TuyaHomeSdk.getHomeManagerInstance().queryHomeList(object : ITuyaGetHomeListCallback {
            override fun onSuccess(homeBeans: MutableList<HomeBean>?) {
                hookLog("tuya sdk query family list success")
                hookLog("tuya sdk query family list size = ${homeBeans?.size}")
                AppConfig.uiHandler().post {
                    successCallback?.invoke(homeBeans)
                }
            }

            override fun onError(errorCode: String?, error: String?) {
                hookLog("tuya sdk query family list fail")
                hookLog("tuya sdk query family list code = $errorCode, error = $error")
                AppConfig.uiHandler().post {
                    "获取家庭列表失败".toast()
                }
            }

        })
    }

    /**
     * @author xhb
     * @version 1.0.0
     * @desc 家庭管理 添加家庭
     */
    @JvmStatic
    fun createFamily(name: String, rooms: List<String>? = null, successCallback: ((bean: HomeBean?) -> Unit)?) {
        TuyaHomeSdk.getHomeManagerInstance().createHome(name, 0.00, 0.00, "", rooms,
            object : ITuyaHomeResultCallback {
                override fun onSuccess(bean: HomeBean?) {
                    hookLog("tuya sdk create family success")
                    hookLog("tuya sdk create family is  ${bean?.toString()}")
                    AppConfig.uiHandler().post {
                        successCallback?.invoke(bean)
                    }
                }

                override fun onError(errorCode: String?, errorMsg: String?) {
                    AppConfig.uiHandler().post {
                        hookLog("tuya sdk create family fail")
                        hookLog("tuya sdk create family code = $errorCode, error = $errorCode")
                        AppConfig.uiHandler().post {
                            "创建家庭失败".toast()
                        }
                    }
                }
            })
    }

    /**
     * @author xhb
     * @version 1.0.0
     * @desc 家庭管理 删除家庭
     */
    @JvmStatic
    fun removeFamily(homeId: Long, successCallback: (() -> Unit)? = null) {
        TuyaHomeSdk.newHomeInstance(homeId).dismissHome(
            object : IResultCallback {
                override fun onSuccess() {
                    hookLog("tuya sdk delete family success")
                    AppConfig.uiHandler().post {
                        successCallback?.invoke()
                    }
                }

                override fun onError(errorCode: String?, errorMsg: String?) {
                    AppConfig.uiHandler().post {
                        hookLog("tuya sdk delete family fail")
                        hookLog("tuya sdk delete family code = $errorCode, error = $errorCode")
                        AppConfig.uiHandler().post {
                            "创建家庭失败".toast()
                        }
                    }
                }
            })
    }

    /**
     * @author xhb
     * @version 1.0.0
     * @desc 家庭管理 获取家庭的详细信息
     */
    @JvmStatic
    fun queryFamilyDetail(homeId: Long, successCallback: ((bean: HomeBean?) -> Unit)? = null) {
        TuyaHomeSdk.newHomeInstance(homeId).getHomeDetail(
            object : ITuyaHomeResultCallback {
                override fun onSuccess(bean: HomeBean?) {
                    hookLog("tuya sdk query family detail success")
                    AppConfig.uiHandler().post {
                        successCallback?.invoke(bean)
                    }
                }

                override fun onError(errorCode: String?, errorMsg: String?) {
                    AppConfig.uiHandler().post {
                        hookLog("tuya sdk query family detail fail")
                        hookLog("tuya sdk query family detail code = $errorCode, error = $errorCode")
                        AppConfig.uiHandler().post {
                            "创建家庭失败".toast()
                        }
                    }
                }
            })
    }

    /**
     * @author xhb
     * @version 1.0.0
     * @desc 家庭管理 新增一个家庭监听
     */
    @JvmStatic
    fun registerTuyaHomeChangeListener(listener: ITuyaHomeChangeListener) {
        TuyaHomeSdk.getHomeManagerInstance().registerTuyaHomeChangeListener(listener)
    }

    /**
     * @author xhb
     * @version 1.0.0
     * @desc 家庭管理 移除一个家庭监听
     */
    @JvmStatic
    fun unRegisterTuyaHomeChangeListener(listener: ITuyaHomeChangeListener) {
        TuyaHomeSdk.getHomeManagerInstance().unRegisterTuyaHomeChangeListener(listener)
    }

    @JvmStatic
    fun queryActivatorToken(homeId: Long, successCallback: ((token: String) -> Unit)?) {
        TuyaHomeSdk.getActivatorInstance().getActivatorToken(homeId,
            object : ITuyaActivatorGetToken {
                override fun onSuccess(token: String) {
                    hookLog("tuya sdk query activator success token = $token")
                    AppConfig.uiHandler().post {
                        successCallback?.invoke(token)
                    }
                }
                override fun onFailure(errorCode: String, errorMsg: String) {
                    hookLog("tuya sdk query activator fail s = errorCode = $errorCode, errorMsg = $errorMsg")
                }
            })
    }

    @JvmStatic
    fun createActivatorBuilder(context: Context, ssid: String, pwd: String, token: String,
                               stepCallback: ((step: String?) -> Unit)? = null,
                               activeSuccessCallback: ((devResp: DeviceBean?) -> Unit)? = null,
                               errorCallback: ((errorMsg: String?) -> Unit)? = null): ActivatorBuilder {
        return with(ActivatorBuilder()) {
            this.context = context
            this.ssid = ssid
            this.password = pwd
            this.activatorModel = ActivatorModelEnum.TY_EZ
            this.timeOut = 120
            this.token = token
            this.setListener(object : ITuyaSmartActivatorListener {
                override fun onStep(step: String?, data: Any?) {
                    hookLog("tuya sdk create activator builder step = $step, data = ${data.toString()}")
                    AppConfig.uiHandler().post {
                        stepCallback?.invoke(step)
                    }
                }

                override fun onActiveSuccess(devResp: DeviceBean?) {
                    hookLog("tuya sdk create activator builder devResp = ${devResp.toString()}")
                    AppConfig.uiHandler().post {
                        activeSuccessCallback?.invoke(devResp)
                    }
                }

                override fun onError(errorCode: String?, errorMsg: String?) {
                    hookLog("tuya sdk create activator builder errorCode = $errorCode, errorMsg = $errorMsg")
                    AppConfig.uiHandler().post {
                        errorCallback?.invoke(errorMsg)
                    }
                }
            })
        }
    }

    fun toggleDeviceState(deviceId: String, isCheck: Boolean) {
        val orderString = "{\"1\": $isCheck}"
        TuyaHomeSdk.newDeviceInstance(deviceId).publishDps(orderString,
                object : IResultCallback {
                    override fun onSuccess() {
                        hookLog("tuya sdk toggle device success")
                    }

                    override fun onError(code: String, error: String) {
                        hookLog("tuya sdk toggle device fail errorCode = $code, errorMsg = $error")
                    }
                })
    }

    fun initTuyaActivator(builder: ActivatorBuilder): ITuyaActivator {
        return TuyaHomeSdk.getActivatorInstance().newMultiActivator(builder)
    }

    private fun hookLog(msg: String) {
        L.setLogSwitcher(AppConfig.isDebug())
        L.d(AppConfig.application().getString(R.string.app_name), msg)
    }
}
